home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1492 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: wkaufman.us.oracle.com!wkaufman
  2. From: wkaufman@wkaufman.us.oracle.com (William Kaufman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Extracting chars from shorts.
  5. Date: 14 Jan 1996 18:13:15 GMT
  6. Organization: Oracle Corporation, Redwood Shores CA
  7. Message-ID: <4dbh3r$4o8@inet-nntp-gw-1.us.oracle.com>
  8. References: <4d13i0$k3s@lastactionhero.rs.itd.umich.edu>
  9. NNTP-Posting-Host: wkaufman.us.oracle.com
  10.  
  11. In article <4d13i0$k3s@lastactionhero.rs.itd.umich.edu> dogcow@monet.ccs.itd.umich.edu (Tom Spindler) writes:
  12. ] I'm trying to extracts individual bytes from a double. The following code
  13. ] doesn't work:
  14. [... type punning ...]
  15. ] One compiler complains that it's an illegal cast, whereas gcc says that the
  16. ] return value is an int.
  17. ] I could do something like ((char *)&v[0]), but then it would crash if I
  18. ] tried to do something with lo(42).
  19. ] Any suggestions? (I already know what endian the code is supposed to run on.)
  20.  
  21.     If you know that, you can drop the structure and replace your macros
  22. with,
  23.  
  24.         #include <limit.h>    /* for CHAR_BIT definition */
  25.  
  26.         #define lo(x)    ((x) & ((1 << CHAR_BIT) - 1))
  27.         #define hi(x)    (lo((x) >> CHAR_BIT))
  28.  
  29.     The first will strip off the least-significant byte (regardless of
  30. endianness and byte size); the second shifts the data down by a byte and
  31. strips off the LSB.  These should handle any expression you've got,
  32. including ones with prefix and postfix operators.
  33.  
  34.                                            -- Bill K.
  35.  
  36. Bill Kaufman               | " While not a master of intellect, the blatantly
  37. wkaufman@us.oracle.com     |   obvious things we take for granted never
  38.                            |   escape his keen eye! "          -- Bob Burden
  39.